<template>
  <section>
    <div class="filter-container">
        <common-input @keyup.enter.native="handleFilter" class="w100" placeholder="商品关键字" v-model="listQuery.keyword" />
        <el-select class="ml10" clearable size="mini" v-model="listQuery.platform" placeholder="来源">
            <el-option
                    v-for="item in platformList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
        </el-select>
        <el-select class="ml10" @change="getCateList(false)" size="mini" v-model="listQuery.parentCateId" placeholder="一级分类">
            <el-option
                    v-for="item in parentCateList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
        </el-select>
        <el-select size="mini" class="ml10" v-model="listQuery.cateId" placeholder="二级分类">
            <el-option
                    v-for="item in cateList"
                    :key="item.id"
                    :label="item.name"
                    :value="item.id">
            </el-option>
        </el-select>
        <el-button size="mini" class="ml10" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
    </div>
    <el-tabs size="mini" :before-leave='leaveTab' v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="出售中" name="1"></el-tab-pane>
      <el-tab-pane label="已下架" name="3"></el-tab-pane>
    </el-tabs>
    <el-alert
            v-if="ids&&ids.length>0"
            show-icon>
        <template slot="title">
            <span>已选择 {{ids.length}} 项</span> <el-button @click="clear()" type="text">清空</el-button> 
            <template v-if="!isSelect">
                <el-button v-if="activeName=='1'" @click="down()" type="text">批量下架</el-button> 
                <el-button v-else-if="activeName=='3'" @click="up()" type="text">批量上架</el-button>
            </template>
            <template v-else>
                <el-button  @click="select()" type="text">选择</el-button> 
            </template>
        </template>
    </el-alert>
    <el-table ref="dataTable" :height="tableHeight" :data="list"
                        @sort-change="tblSort"
                        @selection-change="selectChange"
                style="width: 100%">
            <el-table-column
                    fixed
                    type="selection"
                    width="55">
            </el-table-column>
            <el-table-column align="right" width="80" label="排序" sortable="custom" prop="order_num">
                <template slot-scope="scope">
                    <span>{{scope.row.orderNum}}</span>
                    <i @click="editOrder(scope.row)" class="el-icon-edit ml10" style="cursor:pointer;color:#F4222D;"></i>
                </template>
            </el-table-column>
            <el-table-column align="left" label="" width="120">
                <template slot-scope="scope">
                    <span><img :src="scope.row.imgUrl" style="width:80px;cursor:pointer;" /></span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="商品">
                <template slot-scope="scope">
                    <span>{{scope.row.title}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="来源">
                <template slot-scope="scope">
                    <span>{{scope.row.platformName}}</span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="分类1">
                <template slot-scope="scope">
                    <span v-if="scope.row.parentCateId>0">{{scope.row.parentCateName}}<span v-if="scope.row.cateId>0">-{{scope.row.cateName}}</span><span v-if="scope.row.thirdCateId>0">-{{scope.row.thirdCateName}}</span></span>
                </template>
            </el-table-column>
            <el-table-column align="left" label="分类2">
                <template slot-scope="scope">
                    <span v-if="scope.row.parentCateId2>0">{{scope.row.parentCateName2}}<span v-if="scope.row.cateId2>0">-{{scope.row.cateName2}}</span><span v-if="scope.row.thirdCateId2>0">-{{scope.row.thirdCateName2}}</span></span>
                </template>
            </el-table-column>
            <el-table-column width="100" align="right" label="售价" sortable="custom" prop="price">
                <template slot-scope="scope">
                    <span>￥{{scope.row.price}}</span>
                </template>
            </el-table-column>
            <el-table-column width="100" align="right" label="成交价">
                <template slot-scope="scope">
                    <span>￥{{scope.row.finalPrice}}</span>
                </template>
            </el-table-column>
            <el-table-column width="100" align="right" label="佣金比例" sortable="custom" prop="promotion_rate">
                <template slot-scope="scope">
                    <span>{{scope.row.promotionRate}}%</span>
                </template>
            </el-table-column>
            <el-table-column width="100" align="right" label="佣金" sortable="custom" prop="promotion">
                <template slot-scope="scope">
                    <span>￥{{scope.row.promotion}}</span>
                </template>
            </el-table-column>
            <el-table-column width="100" align="right" label="优惠券" sortable="custom" prop="coupon_discount">
                <template slot-scope="scope">
                    <span>{{scope.row.couponDiscount}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="创建时间" width="150" sortable="custom" prop="created_at">
                <template slot-scope="scope">
                    <span>{{scope.row.createdAt}}</span>
                </template>
            </el-table-column>
            <el-table-column align="center" label="操作" 
                    fixed="right" v-if="!isSelect">
                <template slot-scope="scope">
                    <span>
                        <el-dropdown class="ml10">
                        <el-button

                                type="text">
                            更多<i class="el-icon-arrow-down el-icon--right"></i>
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <!-- <el-dropdown-item @click.native="handleDetail(scope.row)">查看</el-dropdown-item> -->
                            <el-dropdown-item @click.native="handleUpdate(scope.row)">编辑</el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.canUp==1" @click.native="handleUp(scope.row)">上架</el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.canDown==1" @click.native="handleDown(scope.row)">下架</el-dropdown-item>
                            <el-dropdown-item v-if="scope.row.canDelete==1" @click.native="handleDelete(scope.row)">删除</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    </span>
                </template>
            </el-table-column>
    </el-table>
        <div class="pagination-container">
            <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.pageNum" :page-sizes="[20,30, 50]" :page-size="listQuery.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"> </el-pagination>
        </div>

    <el-dialog title="编辑排序" :visible.sync="dialogOrderVisible" :close-on-click-modal="false" width="300px">
        <el-form :model="orderForm" ref="orderForm" label-width="80px">
            <el-form-item label="排序" prop="orderNum">
                <el-input size="mini" type="number" placeholder="" maxlength="3" v-model="orderForm.orderNum" />
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogOrderVisible=false">取消</el-button>
            <el-button :loading="orderLoading" size="mini" type="primary" @click="okOrder">确定</el-button>
        </div>
    </el-dialog>

    <el-dialog title="编辑" :visible.sync="dialogFormVisible" :close-on-click-modal="false" width="500px">
        <el-form :model="form" :rules="rules" ref="form" label-width="150px">
            <el-form-item label="类型" prop="status" v-if="form.platform==3">
                <el-radio-group v-model="form.isTwo">
                    <el-radio :label="0">单人团</el-radio>
                    <el-radio :label="1">双人团</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="分类1：" prop="catIds">
                <el-cascader
                    style="width:100%;"
                    filterable
                    :props="{ value: 'id', label: 'name' }"
                    size="mini"
                    v-model="form.catIds"
                    :options="cateTree"></el-cascader>
            </el-form-item>
            <el-form-item label="分类2：" prop="catIds2">
                <el-cascader clearable
                    style="width:100%;"
                    filterable
                    :props="{ value: 'id', label: 'name' }"
                    size="mini"
                    v-model="form.catIds2"
                    :options="cateTree"></el-cascader>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button size="mini" @click="dialogFormVisible=false">取消</el-button>
            <el-button :loading="saveLoading" size="mini" type="primary" @click="okEdit('form')">确定</el-button>
        </div>
    </el-dialog>

    
  </section>
</template>

<script>
    import {
        retail_product_cat_tree,
        retail_product_list,
        retail_product_delete,
        retail_product_update_order,
        retail_product_detail,
        retail_product_up,
        retail_product_down,
        retail_product_category,
        retail_product_edit
    } from '../../api/retail_product';
    import Viewer from 'viewerjs';
    import 'viewerjs/dist/viewer.css';
    export default {
        components: {
        },
        props: {
            formData: Object
        },
        data() {
            return {
                filterText: '',
                cateTree: [],
                saveLoading: false,
                dialogFormVisible: false,
                isSelect: false,
                viewerId: null,
                orderLoading: false,
                tableHeight: 200,
                cateList: [],
                parentCateList:[],
                platformList: [
                    {
                        id: 1,
                        name: "淘宝"
                    },
                    {
                        id: 2,
                        name: "京东"
                    },
                    {
                        id: 3,
                        name: "拼多多"
                    },
                    // {
                    //     id: 4,
                    //     name: "唯品会"
                    // }
                ],
                list: null,
                listLoading: true,
                listQuery: {
                    pageNum: 1,
                    pageSize: 20,
                    agency: undefined,
                    keyword: undefined,
                    auditStatus: '3',
                    orderCol: "",
                    orderAsc: "",
                    cateId: undefined,
                    parentCateId: undefined,
                    status: '1',
                    getSaleCount: 1,
                    limitUser: undefined,
                    platform: undefined
                },
                total: null,
                activeName: '1',
                currentId: 0,
                checkLoading: false,
                dialogOrderVisible: false,
                orderForm: {
                    id: 0,
                    orderNum: 0,
                },
                productForm: {
                    id: 0,
                    hasSku: 0,
                    skuInfo: [],
                    inventory: 0,
                },
                dialogStockVisible: false,
                stockLoading: false,
                ids: [],
                form: {
                    catIds: [],
                    catIds2: [],
                    parentCateId: undefined,
                    cateId: undefined,
                    thirdCateId: undefined,
                    parentCateId2: undefined,
                    cateId2: undefined,
                    thirdCateId2: undefined,
                    platform: 3,
                    isTwo: 0,
                    id: 0,
                },
                rules: {
                    catIds: [
                        {
                            required: true,
                            message: '请选择商品分类',
                            trigger: 'blur'
                        }
                    ],
                },
            }
        },
        watch: {
            formData: {
                immediate: true,
                handler (val) {
                    this.isSelect = val.is_select;

                    // console.log(val)
                }
            },
            filterText(val) {
                this.$refs.tree.filter(val);
            }
        },
        mounted() {
            const that = this

            window.onresize = () => {

                return (() => {

                    that._getTableHeight()

                })()
            }
        },
        created() {
            this._getTableHeight();
            this.getParentCateList();
            this.getTree();
            this.getList();
        },
        methods: {
            okEdit(formName) {
                this.$refs[formName].validate(valid => {
                    if(valid) {
                        this.form.parentCateId = (this.form.catIds && this.form.catIds.length > 0) ? this.form.catIds[0] : 0;
                        this.form.cateId = (this.form.catIds && this.form.catIds.length > 1) ? this.form.catIds[1] : 0;
                        this.form.thirdCateId = (this.form.catIds && this.form.catIds.length > 2) ? this.form.catIds[2] : 0;


                        this.form.parentCateId2 = (this.form.catIds2 && this.form.catIds2.length > 0) ? this.form.catIds2[0] : 0;
                        this.form.cateId2 = (this.form.catIds2 && this.form.catIds2.length > 1) ? this.form.catIds2[1] : 0;
                        this.form.thirdCateId2 = (this.form.catIds2 && this.form.catIds2.length > 2) ? this.form.catIds2[2] : 0;

                        this.saveLoading = true;
                        retail_product_edit(this.form).then((res)=>{
                            this.saveLoading = false;
                            this.$message.success("操作已执行");
                            this.dialogFormVisible = false;

                            this.getList();
                        }).catch((err)=>{
                            this.saveLoading = false;

                        })
                    }
                });
            },
            getTree() {
                retail_product_cat_tree(0).then((res)=>{
                    this.cateTree = res.data
                }).catch((err)=>{
                });
            },
            filterNode(value, data) {
                if (!value) return true;
                return data.name.indexOf(value) !== -1;
            },
            handleUpdate(row) {
                // retail_product_detail(row.id).then((res)=>{
                //     this.form.platform = res.data.platform;
                //     this.form.isTwo = res.data.isTwo;
                //     this.form.id = res.data.id;
                //     this.form.catIds = res.data.cateIds;

                //     this.filterText = "";
                //     this.dialogFormVisible = true;

                //     // console.log(this.productForm)
                // }).catch((err)=>{

                // })
                let catIds = [];
                if(row.parentCateId > 0) {
                    catIds.push(""+row.parentCateId);

                    if(row.cateId > 0) {
                        catIds.push(""+row.cateId);

                        if(row.thirdCateId > 0) {
                            catIds.push(""+row.thirdCateId);
                        }
                    }
                }
                this.form.catIds = catIds;

                let catIds2 = [];
                if(row.parentCateId2 > 0) {
                    catIds2.push(""+row.parentCateId2);

                    if(row.cateId2 > 0) {
                        catIds2.push(""+row.cateId2);

                        if(row.thirdCateId2 > 0) {
                            catIds2.push(""+row.thirdCateId2);
                        }
                    }
                }
                this.form.catIds2 = catIds2;
                this.form.platform = row.platform;
                this.form.isTwo = row.isTwo;
                this.form.id = row.id;

                // // console.log(row);
                console.log(this.form)
                this.dialogFormVisible = true;
            },
            _getTableHeight() {
                this.tableHeight = window.innerHeight - 250
            },
            getList() {
                this.listLoading = true;
                retail_product_list(this.listQuery).then(response => {
                    this.list = response.data.list;
                    this.total = response.data.total;
                    this.listLoading = false;
                })
            },
            getParentCateList() {
                retail_product_category(0).then((res)=>{
                    this.parentCateList = res.data;
                    this.cateList = []
                }).catch((err)=>{
                    this.parentCateList = []
                    this.cateList = []
                });
            },
            getCateList() {
                this.listQuery.cateId = undefined;
                retail_product_category(this.listQuery.parentCateId).then((res)=>{
                    this.cateList = res.data;
                }).catch((err)=>{
                    this.cateList = []
                });
            },
            handleFilter() {
                this.listQuery.pageNum = 1;
                this.getList();
            },
            handleSizeChange(val) {
                this.listQuery.pageSize = val;
                this.getList();
            },
            handleCurrentChange(val) {
                this.listQuery.pageNum = val;
                this.getList();
            },
            handleClick(tab, event) {
                this.listQuery.status = this.activeName;
                this.handleFilter();
            // console.log(this.activeName)
            },
            leaveTab(activeName, oldActiveName) {
            // console.log(activeName)
            // return false;
            },
            handleDelete(row) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        retail_product_delete(row.id)
                            .then(() => {
                                this.$message.success("商品删除成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            handleDetail(row) {
                let {href} = this.$router.resolve({path: '/goods_detail?id=' + row.id});
                window.open(href, '_blank');
            },
            dialogClose() {
                this.$refs.form.resetFields();
            },
            tblSort(d) {
                this.listQuery.orderCol = d.prop;
                this.listQuery.orderAsc = d.order;

                this.handleFilter();
            },
            editOrder(row) {
                this.orderForm.id = row.id;
                this.orderForm.orderNum = row.orderNum;

                // console.log(this.orderForm)
                this.dialogOrderVisible = true;
            },
            okOrder() {
                this.orderLoading = true;
                retail_product_update_order(this.orderForm).then((res)=>{
                    this.orderLoading = false;
                    this.dialogOrderVisible = false;
                    this.$message.success("排序已更新");

                    this.getList();
                }).catch((err)=>{
                    this.orderLoading = false;
                })
            },
            editStock(row) {
                retail_product_detail(row.id).then((res)=>{
                    this.productForm.id = res.data.id;
                    this.productForm.hasSku = res.data.hasSku;
                    this.productForm.inventory = res.data.inventory;
                    this.productForm.skuInfo = res.data.skuInfo;

                    this.dialogStockVisible = true;

                    console.log(this.productForm)
                }).catch((err)=>{

                })
            },
            makeMinStock() {
                let p = 0;
                if(this.productForm.skuInfo && this.productForm.skuInfo.length > 0) {
                    this.productForm.skuInfo.forEach((item)=>{
                        if(item.inventory) {
                            p += Number(item.inventory) || 0
                        }
                    })
                }
                this.productForm.inventory = p;
            },
            okStock() {
                this.stockLoading = true;
                product_update_stock(this.productForm).then((res)=>{
                    this.stockLoading = false;
                    this.dialogStockVisible = false;
                    this.$message.success("库存已更新");

                    this.getList();
                }).catch((err)=>{
                    this.stockLoading = false;
                })
            },
            selectChange(selection) {
                this.ids = [];
                if(selection && selection.length > 0) {
                    selection.forEach((item)=>{
                        this.ids.push(item.id)
                    })
                }
                // console.log(this.ids)
            },
            clear() {
                this.$refs.dataTable.clearSelection();
            },
            up(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('确定上架?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        retail_product_up({
                            ids: ids
                        })
                            .then(() => {
                                this.$message.success("商品上架成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            down(ids) {
                if(!ids || ids.length < 1) {
                    ids = this.ids;
                }
                this.$confirm('确定下架?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                })
                    .then(() => {
                        retail_product_down({
                            ids: ids
                        })
                            .then(() => {
                                this.$message.success("商品下架成功");
                                this.getList();
                            });
                    }).catch(()=>{});
            },
            handleUp(row) {
                this.up([row.id]);
            },
            handleDown(row) {
                this.down([row.id]);
            },
            select() {
                this.$emit('okSelect', this.ids);
            }
        }
    };
</script>
<style lang="scss" scoped>
</style>
